package com.zkh.myframe.interceptor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zkh.myframe.core.Chain;
import com.zkh.myframe.exception.BaseException;
import com.zkh.myutils.io.log.Logger;
import com.zkh.myutils.net.upload.FileItem;
import com.zkh.myutils.net.upload.UploadException;
import com.zkh.myutils.net.upload.UploadFile;
import com.zkh.myutils.net.upload.Uploader;
import com.zkh.myutils.system.UploadConfigBean;
import com.zkh.myutils.utils.StringUtils;

/**
 * 文件上传拦截器
 * @author zkh
 */
public class UploadFileInterceptor implements Interceptor {
	/**
	 * 上传文件集合字段名称
	 */
	public static String UPLOAD_FORM_FILES = "uploadFormFiles";
	/**
	 * 上传表单字段
	 */
	public static String UPLOAD_FORM_FIELDS = "uploadFormFields";
	/**
	 * 上传异常字段
	 */
	public static String UPLOAD_FILE_LIST_EXCEP = "uploadFileListException";

	//上传配置
	public static UploadConfigBean uploaderConfig = UploadConfigBean.getConfig();

	@Override
	public void doFilter(HttpServletRequest request, HttpServletResponse response, Chain chain) throws Exception{
		//检测是否是文件上传
		if(Uploader.isUpload(request)){
			//唯一标识key
			String key = request.getParameter("key");
			//上传对象
			Uploader uploader = StringUtils.isEmpty(key) ? new Uploader() : new Uploader(key);
			//表单数据保存
			Map<String, String[]> map = new HashMap<>();
			//上传文件保存
			Map<String, List<UploadFile>> uploadFileMap = new TreeMap<>();
	        //解析请求参数
	        try {
				//获取上传文件
				List<FileItem> items = uploader.parseUpload(request, uploaderConfig, true);
				//遍历集合
				for(FileItem item:items){
					//如果是表单数据
					if(!item.isFile()){
						map.put(item.getFieldname(), item.getFieldValueList().toArray(new String[0]));
					}
					//否则为文件流
					else{
						uploadFileMap.put(item.getFieldname(), item.getUploadFileList());
					}
				}
				//将上传的文件集合保存在request域中
				request.setAttribute(UPLOAD_FORM_FILES, uploadFileMap);
				//将上传时的表单数据保存在request域中
				request.setAttribute(UPLOAD_FORM_FIELDS, map);
			} catch (BaseException | UploadException e){
				//将上传时出现的异常保存在request域中
				request.setAttribute(UPLOAD_FILE_LIST_EXCEP, e.getMessage());
			} catch(Exception e){
				//未知异常需打印异常信息
				Logger.error(e);
				//保存未知错误信息
				request.setAttribute(UPLOAD_FILE_LIST_EXCEP, "未知错误");
			}
		}
		
		//释放链
		chain.nextChain();
	}

}